package edu.hawaii.ics.pjdb.worker.command_runners;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.SQLException;

import org.apache.thrift.TException;

import edu.hawaii.ics.pjdb.types.RunScriptCommand;
import edu.hawaii.ics.pjdb.types.WorkerCommand;
import edu.hawaii.ics.pjdb.util.ScriptRunner;

public class DbScriptRunner extends CommandRunner {
    private final ScriptRunner scriptRunner;

    public DbScriptRunner(Connection localDb) {
        super(localDb);
        this.scriptRunner = new ScriptRunner(localDb, false, true);
    }

    @Override
    public void execute(WorkerCommand workerCommand) throws TException,
            SQLException {
        RunScriptCommand cmd = workerCommand.getCommand().getRunScriptCmd();
        Reader scriptReader = new StringReader(cmd.getScript());

        try {
            scriptRunner.runScript(scriptReader);
        } catch (IOException e) {
            // This should never happen since we're using a StringReader...
            throw new RuntimeException(e);
        }
    }
}
